package io.terminus.lego.shinda.web.filter

import io.terminus.lego.shinda.web.context.BindingContext
import io.terminus.lego.shinda.web.controller.BindingController
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import javax.servlet.*
import javax.servlet.http.HttpServletRequest

/**
 * 社交账户绑定功能的filter
 * 职能是将绑定信息设置到上下文中，以便Oauth2登录的时候知道此次是绑定操作
 * @author wangmeng
 * @date 2018/4/16
 */
@Component
class BindContextFilter : Filter {

    val logger = LoggerFactory.getLogger(javaClass)

    override fun destroy() {
        logger.debug("BindContextFilter destory")
    }

    override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
        try {
            //将session 信息中的绑定信息设置到BindingContext中
            request as HttpServletRequest
            val userId = request.session.getAttribute(BindingController.BIND_SESSION_KEY_USER_ID)
            val target = request.session.getAttribute(BindingController.BIND_SESSION_KEY_TARGET)

            BindingContext.username.set(userId?.toString())
            BindingContext.target.set(target?.toString())
            chain.doFilter(request, response)
        } finally {
            //将BindingContext中的信息删除，避免线程复用出现脏数据
            BindingContext.username.remove()
            BindingContext.target.remove()
        }
    }

    override fun init(filterConfig: FilterConfig?) {
        logger.debug("BindContextFilter init")
    }

}